package com.qf.fengmimall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fengmimall.constant.Constants;
import com.qf.fengmimall.ex.UserException;
import com.qf.fengmimall.until.SaltUtils;
import com.qf.fengmimall.user.entity.Users;
import com.qf.fengmimall.user.mapper.UsersMapper;
import com.qf.fengmimall.user.service.IUsersService;
import com.qf.fengmimall.vo.UserVo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author lx
 * @since 2023-02-13
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void registe(UserVo userVo) throws UserException {
        String username = userVo.getUsername();
        //校验两次密码是否一直
        if (!userVo.getPassword().equals(userVo.getRepassword())) {
            throw new UserException("两次密码不同");
        }
        Users users = getOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, username));
        if (users != null) {
            throw new UserException("用户已存在");
        } else {
            users = new Users();
        }
        String salt = SaltUtils.getSalt(Constants.SALTLENGTH);
        Md5Hash md5Hash = new Md5Hash(userVo.getPassword(), salt, Constants.HASHCOUNT);
        users.setPassword(md5Hash.toHex());
        users.setUsername(userVo.getUsername());
        users.setUserRegtime(new Date());
        users.setUserModtime(new Date());
        users.setSalt(salt);
        save(users);
    }
}
